﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
    public class UserRoleRepository : Repository<UserRole>, IUserRoleRepository
    {
        protected override Expression<Func<UserRole, int>> PrimaryKeyExpression => r => r.Id;

        public UserRoleRepository(ApiDBContent context) : base(context)
        {
        }

        protected override IEnumerable<UserRole> IncludeRelationships(IEnumerable<UserRole> entities, ApiDBContent db)
        {
            SetRoleInfo(entities, db);
            return entities;
        }

        private void SetRoleInfo(IEnumerable<UserRole> entities, ApiDBContent db)
        {
            if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, UserRoleRelationship.RoleInfo))
            {
                return;
            }

            var roleIds = entities.Select(r => r.RoleId).ToList();
            var userRoles = db.AdminRole.Where(r => roleIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r.Name);
            foreach (var entity in entities)
            {
                if (userRoles.TryGetValue(entity.RoleId, out string roleName))
                {
                    entity.RoleName = roleName;
                }
            }
        }
    }
}
